package cn.haeloong.lucene;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;

import java.nio.file.Paths;

import static org.apache.lucene.document.Field.Store.YES;

public class IndexReps {
    @Test
    public void createIndex()throws Exception{
        //创建好的索引文件存放的目录
        FSDirectory directory = FSDirectory.open(Paths.get("D:/myIndex"));
        //分词器StandarAnalyzer标准分词器
        StandardAnalyzer analyzer = new StandardAnalyzer();
        //配置对象
        IndexWriterConfig config = new IndexWriterConfig(analyzer);

        //创建索引库的对象
        IndexWriter iw = new IndexWriter(directory, config);


        //获取文档
        File fileDirs = new File("D:\\java基础重点\\实战-30期\\day07\\5 Lucene&Solr\\资料\\docment");
        //获取该目录下的所有文件
        File[] files = fileDirs.listFiles();

        for (File file : files) {
            //构建文档对象

            Document document = new Document();
            //文件的名称，文件的内容，文件的size，文件的路径
            String fileName = file.getName();
            String fileContet = FileUtils.readFileToString(file, "UTF-8");
            long fileSize = FileUtils.sizeOf(file);
            String filePath = file.getAbsolutePath();
            //System.out.println("filePath = " + filePath);

            document.add(new StringField("fileName",fileName, YES));
            document.add(new StringField("fileContet",fileContet,Field.Store.NO));
            document.add(new LongPoint("fileSize",fileSize));
            document.add(new StringField("filePath",filePath,Field.Store.YES));

            iw.addDocument(document);

        }

        //建立索引库
        iw.flush();
        iw.commit();

        iw.close();

    }
}
